<?php
namespace app\client\controller;

class Wallet extends Base {
    public function __construct() {
        parent::__construct();
    }
    
    public function balance() {
        $amount = model('UserWallet')->where(['user_id' => $this->userid])->value('amount');
        return successResult(['balance' => $amount]);
    }
    
    public function withdrawal() {
        $amount = request()->post('amount', 0, 'floatval');
        if($amount < 1 || $amount > 5000) {
            return errorResult();
        }
        
        $userId = $this->userid;
        
        $time = time();
        $today = date('Y-m-d 00:00:00', $time);
        $today = strtotime($today);
        
        $logModel = model('WithdrawalOrder');
        $log = $logModel->findOne(['user_id' => $userId, 'day' => $today], ['id']);
        if(!empty($log)) {
            return errorResult('今天已经提现过');
        }
        
        $orderNo = getOrderNo($userId);
        $orderData = [
            'user_id' => $userId,
            'order_no' => $orderNo,
            'amount' => $amount,
            'actual_amount' => roundNumber($amount * (1 - 0.006), 2),
            'day' => $today
        ];
        
        $model = model('UserWallet');
        
        $model->startTrans();
        
        try {
            $balance = $model->where(['user_id' => $this->userid])->lock(true)->value('amount');
            if($amount > $balance) {
                $model->rollback();
                return errorResult('账号余额不足呢~');
            }
            
            $rs = $model->modify(['user_id' => $userId], ['amount' => $balance - $amount]);
            if(!$rs) {
                $model->rollback();
                return errorResult();
            }
            
            $wx = new \app\client\wxpay\Mmpaymkttransfers(session('user')['openid']);
            $wx->setOrder(['amount' => $orderData['actual_amount'], 'order_no' => $orderNo]);
            $res = $wx->transfer();
            if($res['err'] == 1) {
                $model->rollback();
                return errorResult($res['msg']);
            }
            
            $model->commit();
            
            $orderData['trade_no'] = $res['payment_no'];
            $orderData['payment_time'] = strtotime($res['payment_time']);
            
            $orderId = $logModel->add($orderData);
            if($orderId) {
                $rs = model('UserFinanceLog')->add(['user_id' => $userId, 'before_amount' => $balance, 'amount' => -$amount, 'type' => 6, 'related_id' => $orderId, 'add_time' => $time]);
                if(!$rs) {
                    $model->rollback();
                    return errorResult();
                }
            }
            
            return successResult();
            
        } catch (\Exception $e) {
            $model->rollback();
            return errorResult();
        }
        
    }
    
    public function log() {
        $params = request()->get();
        $pk = isset($params['lastPk']) ? intval($params['lastPk']) : 0;
        $pageSize = isset($params['pageSize']) ? intval($params['pageSize']) : 20;
        
        $where = [['user_id', '=', $this->userid]];
        
        if($pk > 0) {
            $where[] = ['id', '<', $pk];
        }
        
        $list = model('UserFinanceLog')->where($where)->field(['id', 'type', 'add_time', 'related_id', 'amount'])->order('id desc')->limit($pageSize)->select()->toArray();
        return successResult(['list' => $list]);
    }
}












